package vip.liux.front.application.service.coupon;

import org.springframework.stereotype.Service;
import vip.liux.application.dots.ListResultDto;
import vip.liux.contracts.models.coupon.Coupon;
import vip.liux.contracts.models.coupon.UserCouponDomainService;
import vip.liux.contracts.repositories.coupon.CouponRepository;
import vip.liux.contracts.shared.value.ReceivedRecord;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CouponService {

    private final CouponRepository couponRepository;
    private final UserCouponDomainService userCouponDomainService;

    public CouponService(CouponRepository couponRepository, UserCouponDomainService userCouponDomainService) {
        this.couponRepository = couponRepository;
        this.userCouponDomainService = userCouponDomainService;
    }

    /**
     * 查询可用优惠券
     *
     * @return 可用优惠券数据传输对象列表
     */
    public ListResultDto<ShopCouponDto> queryAvailableCoupons() {
        // 查询可用优惠券
        List<Coupon> list = couponRepository.findQueryAvailableCoupons();

        // 获取优惠券领取记录
        Map<String, ReceivedRecord> record = userCouponDomainService.getReceivedRecords(
                list.stream().map(Coupon::getCouponNo).collect(Collectors.toSet())
        );

        // 转换为 Dto 并返回
        return new ListResultDto<>(list.stream().map(c -> AutoMapperProfile.INSTANCE.toShopCouponDto(c, record)).toList());
    }
}
